package com.share51.novel.common.parse;

import com.google.common.collect.Lists;
import com.share51.novel.common.StatusConstant;
import com.share51.novel.common.enums.NovelSiteEnums;
import com.share51.novel.config.CrawlSite;
import com.share51.novel.entity.Chapter;
import com.share51.novel.entity.Crawl;
import com.share51.novel.entity.Novel;
import com.share51.novel.init.ApplicationCached;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.share51.novel.common.enums.NovelSiteEnums.NOVEL_SITE_1;

/**
 * 小说解析
 *
 * @author gb
 */
public class NovelParse {

    /**
     * 小说页面解析
     *
     * @param html
     * @param novelSite
     * @return
     */
    public static Novel parseNovel(String html, NovelSiteEnums novelSite,String sourceUrl,String hostName){
        Novel novel=null;
        if (StringUtils.isBlank(html)){
            return null;
        }
        switch (novelSite) {
            case NOVEL_SITE_1:
                novel=parseNovelSite1(html,sourceUrl,hostName,NOVEL_SITE_1.getCode());
            default:
        }
        return novel;
    }

    /**
     * 解析小说详情
     * @param html
     * @return
     */
    private static Novel parseNovelSite1(String html,String sourceUrl,String hostName,int site) {
        Novel novel=new Novel();
        Document document = Jsoup.parse(html);
        document.setBaseUri(sourceUrl);
        String name = document.select("meta[property=og:title]").attr("content");
        String author=document.select("meta[property=og:novel:author]").attr("content");
        String icon=document.select("meta[property=og:image]").attr("content");
        String seriesStatus=document.select("meta[property=og:novel:status]").attr("content");
        String lastChapter=document.select("meta[property=og:novel:latest_chapter_name]").attr("content");
        String introduce=document.select("meta[property=og:description]").attr("content");
        String number=document.select("div.small>span:nth-child(4)").html();
        novel.setName(name);
        novel.setAuthor(author);
        novel.setIcon(icon);
        novel.setSeriesStatus(getSeriesStatus(seriesStatus));
        novel.setNumber(Integer.parseInt(number.replace("字数：","")));
        novel.setLastChapter(lastChapter);
        novel.setIntroduce(introduce);
        novel.setChapterList(getChapterList(document,hostName,site));
        return novel;
    }

    /**
     * 提取小说详情页的章节列表
     * @param document
     */
    private static List<Chapter> getChapterList(Document document,String hostName,int site){
        List<Chapter> list=new ArrayList<>();
        final Elements chapters = document.select("div.listmain>dl dd>a");
        for (int i=12;i<chapters.size();i++){
            Element chapter=chapters.get(i);
            String url=chapter.absUrl("href");
            if (ApplicationCached.existChapterUrl(site+":"+url.replace(hostName,""))){
                // 此小说章节已存在
                continue;
            }
            String name=chapter.text();
            list.add(new Chapter(name,url,i-11));
        }
        return list;
    }

    private static int getSeriesStatus(String status){
        if ("连载中".equals(status)){
            return StatusConstant.NovelStatus.NOVEL_SERIES;
        }
        if ("完结".equals(status)){
            return StatusConstant.NovelStatus.NOVEL_END;
        }
        return StatusConstant.NovelStatus.NOVEL_SERIES;
    }

    /**
     * 小说分类解析
     *
     * @param html
     * @param novelSite
     */
    public static List<Crawl> parseCategory(String html, NovelSiteEnums novelSite) {
        List<Crawl> list = Collections.emptyList();
        if (StringUtils.isBlank(html)) {
            return list;
        }
        switch (novelSite) {
            case NOVEL_SITE_1:
                list=parseCategorySite1(html);
            default:
        }
        return list;
    }

    /**
     * 解析笔趣阁小说分类列表
     *
     * @param html
     * @return
     */
    private static  List<Crawl> parseCategorySite1(String html){
        List<Crawl> list =new ArrayList<>();
        Document document = Jsoup.parse(html);
        Elements lis = document.select("div.up>div.l.bd>ul>li");
        for (Element element:lis){
            String type = element.select("span.s1").text();
            String author = element.select("span.s4").text();
            String name = element.select("span.s2").text();
            String url=element.select("span.s2>a").attr("href");
            Novel novel=new Novel();
            novel.setName(name);
            novel.setAuthor(author);
            novel.setCategory(ApplicationCached.getCategoryCode(type));
            Crawl crawl=new Crawl();
            crawl.setNovel(novel);
            crawl.setUrl(url);
            list.add(crawl);
        }
        return list;
    }

    public static String parseDetail(String html, Integer site) {
        String result="";
        if (StringUtils.isBlank(html)) {
            return result;
        }
        switch (NovelSiteEnums.of(site)) {
            case NOVEL_SITE_1:
                result=getHtmlDetail1(html);
            default:
        }
        return result;
    }

    private static String getHtmlDetail1(String html){
        Document parse = Jsoup.parse(html);
        return parse.select("#content.showtxt").html();
    }

    public static List<Chapter> parseChapter(String html, NovelSiteEnums site, Integer orderIndex,String hostName) {
        List<Chapter> list = Collections.emptyList();
        if (StringUtils.isBlank(html)) {
            return list;
        }
        switch (site) {
            case NOVEL_SITE_1:
                list=parseChapter1(html,orderIndex,site.getCode(),hostName);
            default:
        }
        return list;
    }

    private static List<Chapter> parseChapter1(String html,int orderIndex,int site,String hostName){
        List<Chapter> list= Lists.newArrayList();
        Document document = Jsoup.parse(html);
        final Elements chapters = document.select("div.listmain>dl dd>a");
        int size=chapters.size();
        List<Element> elements = chapters.subList(size - orderIndex - 12, size);
        if (elements.size()>0){
            for (Element element:elements){
                String url=element.absUrl("href");
                if (ApplicationCached.existChapterUrl(site+":"+url.replace(hostName,""))){
                    // 此小说章节已存在
                    continue;
                }
                orderIndex++;
                String name=element.text();
                list.add(new Chapter(name,url,orderIndex));
            }
        }
        return list;
    }
}
